<template>
  <div class="ele-body">
    <el-card shadow="never" v-loading="loading">
      <div class="_card">
        <div class="_form">
          <el-form ref="form"
                   :rules="rules"
                   :model="form"
                   label-width="100px">
            <div class="form-title">作业打标</div>
            <el-form-item v-if="form.operation_no" label="作业编号：">
              <el-input v-model="form.operation_no" disabled></el-input>
            </el-form-item>
            <el-form-item label="作业类别：" prop="operation_category" required>
              <operation-category-select
                v-model="form.operation_category"
              ></operation-category-select>
            </el-form-item>
            <el-form-item label="上报单位：" prop="organization_id" required>
              <organization-select
                :model_type="'illegal'"
                v-model="form.organization_id"
              ></organization-select>
            </el-form-item>
            <el-form-item label="打标分类：" prop="exception_category" required>
              <exception-category-select type="illegal" :unit="form.organization_id"
                                         v-model="form.exception_category"></exception-category-select>
            </el-form-item>
            <el-form-item label="打标地址：" prop="address" required>
              <el-cascader
                clearable
                v-model="form.area_id"
                class="ele-fluid"
                placeholder="请选择省市区"
                :options="regions"
                popper-class="ele-pop-wrap-higher"
                @change="changeArea"
              />
              <el-input
                v-model="form.address"
                :readonly="form.address?false:true"
                placeholder="请在地图上选择详细地址"
              ></el-input>
              <el-button size="mini" style="width: 100%; margin-top: 4px" @click="goHistory" v-if="form.operation_no">
                查看历史标记记录
              </el-button>
              <!-- <div @click="goHistory" class="logDiv" v-if="form.operation_no">查看历史标记记录</div> -->
            </el-form-item>
            <el-form-item label="单位是否可见：">
              <el-select
                clearable
                v-model="form.organization_show"
                placeholder="请选择单位是否可见"
                class="ele-fluid"
              >
                <el-option label="可见" :value="1"/>
                <el-option label="不可见" :value="0"/>
              </el-select>
            </el-form-item>
            <el-form-item label="是否处罚：" v-if="form.operation_category!==2">
              <el-select
                clearable
                v-model="form.penalty"
                placeholder="请选择是否处罚"
                class="ele-fluid"
              >
                <el-option label="是" :value="1"/>
                <el-option label="否" :value="0"/>
              </el-select>
            </el-form-item>
            <el-form-item label="审核员：">
              <el-checkbox-group @change="bindCheckBox"
                                 v-model="checkList"
                                 :min="1">
                <el-checkbox v-for="user in userlist" :label="user" :key="user.id">{{ user.realname }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="备注信息:">
              <el-input
                :rows="3"
                clearable
                type="textarea"
                :maxlength="200"
                v-model="form.description"
                placeholder="请输入备注信息"
              />
            </el-form-item>
            <el-form-item label="异常照片:">
              <upload-image :limit="3" v-model="form.images"></upload-image>
            </el-form-item>
            <el-form-item>
              <el-button :loading="compareLoading" @click="compareNow">立即对比</el-button>
              <el-button @click="adjustDifference">调整差异</el-button>
            </el-form-item>
            <el-form-item>
              <el-button :loading="saveLoading" type="primary" @click="save">{{
                  form.id ? '保 存' : '立即创建'
                }}
              </el-button>
              <el-button @click="$router.back()">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
        <!-- 点击获取位置 -->
        <MapContainer ref="map" @callback="mapCb" :def-marker="form.lnglat" :icon="iconType" style="margin-top:-560px"/>

        <!-- 调整差异的弹窗 -->
        <div v-if="showAdjustModal">
          <adjust-difference :visible.sync="showAdjustModal" title="调整差异" :images="form.images" @callback="handleImagesChange" :markers="form.diff_points"/>
        </div>

      </div>
    </el-card>
  </div>
</template>

<script>
import uploadImage from '@/components/uploadImage'
// import regions from 'ele-admin/packages/regions'
import organizationSelect from '@/components/organizationSelect'
import exceptionCategorySelect from '@/components/exceptionCategorySelect'
import operationCategorySelect from '@/components/operationCategorySelect'
import MapContainer from '@/components/Map/MapContainer'
import AdjustDifference from './adjust-difference'
import { regionData } from 'element-china-area-data'

export default {
  name: 'illegalEdit',
  components: {
    uploadImage,
    organizationSelect,
    exceptionCategorySelect,
    operationCategorySelect,
    MapContainer,
    AdjustDifference
  },
  data() {
    return {
      regions: regionData,
      loading: false,
      saveLoading: false,
      id: 0,
      form: {
        id: 0,
        operation_no: '',
        organization_id: null,
        operation_category: null,
        exception_category: null,
        area_id: [],
        province: '12',
        city: '12',
        county: '12',
        street: '12',
        address: '',
        organization_show: 1,
        penalty: 0,
        description: '',
        images: [],
        latitude: '',
        longitude: '',
        log_id: '',
        shen_ids: '',
        lnglat: [],
        diff_points:[]
      },
      rules: {
        operation_category: [
          {required: true, message: '请选择作业类别', trigger: ['change', 'blur']}
        ],
        organization_id: [
          {required: true, message: '请选择上报单位', trigger: ['change', 'blur']}
        ],
        exception_category: [
          {required: true, message: '请选择巡查分类', trigger: ['change', 'blur']}
        ],
        address: [
          {required: true, message: '请选择打标地址', trigger: ['change', 'blur']}
        ]
      },
      list: [],
      userlist: [],
      checkList: [],
      showAdjustModal: false,
      compareLoading:false
    }
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.info(to.query.id)
    })
  },
  beforeRouteLeave(to, from, next) {
    this.form = {
      id: 0,
      operation_no: '',
      organization_id: null,
      operation_category: null,
      exception_category: null,
      area_id: [],
      province: '12',
      city: '12',
      county: '12',
      street: '12',
      address: '',
      organization_show: 1,
      penalty: 0,
      description: '',
      images: [],
      latitude: '',
      longitude: '',
      log_id: '',
      shen_ids: '',
      lnglat: []
    }
    this.$refs['form'].resetFields()
    next()
  },
  computed: {
    unitid: function () {
      return this.form.organization_id
    },
    address : function() {
      return this.form.address
    },
    iconType() {
			console.log("111", this.form.operation_category,(Number(this.form.operation_category)).toString())
			if (this.form.operation_category) {
				return (this.form.operation_category).toString()
			} else{ 
				return ''
			}
		}
  },
  watch: {
    unitid: {
      handler(val) {
        if (val) {
          this.getuserlist()
        }
      },
      deep: true
    },
    address: {
      handler: function (val) {
        if(val && ! this.form.id){
          this.getLastImageByAddress()
        }
      }
    }
  },
  methods: {
    // 点击地图回调
    mapCb(data) {
      console.log('点击地图回调', data)

      this.form.area_id = this.get(data.adcode)
      this.form.address = data.address
      this.form.longitude = data.lnglat[0]
      this.form.latitude = data.lnglat[1]
    },
    changeArea(val) {
      this.form.address = ''
      const getLabel = function (val, arr, index = 0, res = []) {
        for (let i in arr) {
          if (arr[i].value === val[index]) {
            res.push(arr[i].label)
            if (index === val.length - 1) {
              return res
            } else {
              return getLabel(val, arr[i].children, ++index, res)
            }
          }
        }
      }
      let city = getLabel(val, this.regions)
      this.$refs.map.setCenterByLocation(city.join())
    },
    // 根据区域id获取 省市区id
    get(value, arr = this.regions) {
      for (const obj of arr) {
        if (obj.value === value) {
          return [obj.value, ...this.get(value, obj.children || [])]
        }

        if (obj.children) {
          const res = this.get(value, obj.children)

          if (res.length) {
            return [obj.value, ...res]
          }
        }
      }

      return []
    },
    async getOperationNo() {
      this.$http.post('/illegal/getOperationNo').then(res => {
        this.form.operation_no = res.data.data
      })
    },
    getuserlist() {
      this.userlist = []
      this.$http.post('/user/index?page=1&limit=999&unit_id=' + this.unitid).then(res => {
        if (res.data.data && res.data.data.length > 0) {
          res.data.data.forEach(e => {
            this.userlist.push({id: e.id, realname: e.realname})
          })

          if (this.form.shen_ids) {
            this.userlist.forEach(e => {
              if (this.form.shen_ids.indexOf(e.id.toString()) != -1) {
                this.checkList.push(e)
              }
            })
          }
        }
      })
    },
    bindCheckBox() {
      let ids = ''
      this.checkList.forEach(e => {
        ids += e.id + ','
      })
      this.form.shen_ids = ids.substring(0, ids.length - 1)
    },
    getList() {
      this.$http
        .post('/illegal/getLog', {operation_no: this.form.operation_no})
        .then((res) => {
          if (res.data.code === 0) {
            for (let i in res.data.data) {
              this.list.push({
                ...res.data.data[i],
                operation_category_name:(res.data.data[i].operation_category == 1 ?'异常':res.data.data[i].operation_category == 2 ?'正常':'已处罚'),
								images:res.data.data[i].images_arr,
                lnglats: [Number(res.data.data[i].longitude), Number(res.data.data[i].latitude)]
              })
            }
          } else {
            this.$message.error(res.data.msg)
          }
        })
        .catch((e) => {
          this.$message.error(e.message)
        })
    },
    info(id) {
      if (!id) {
        this.getOperationNo()
        return
      }
      this.loading = true
      this.$http
        .post('/illegal/info', {id: id})
        .then((res) => {
          this.loading = false
          if (res.data.code === 0) {
            this.form = res.data.data
            if (this.form.longitude && this.form.latitude) {
              this.form.lnglat = [this.form.longitude || '', this.form.latitude || '']
              this.$refs.map.setMarker(this.form.lnglat)
            } else {
              // this.$refs.map.setCenterByLocation(this.regions.getLabel(this.form.area_id))
            }
          } else {
            this.$message.error(res.data.msg)
          }
        })
        .catch((e) => {
          this.loading = false
          this.$message.error(e.message)
        })
    },
    save() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.form.street = '12'
          this.saveLoading = true
          this.$http
            .post('/illegal/edit', this.form)
            .then((res) => {
              this.saveLoading = false
              if (res.data.code === 0) {
                this.$message({type: 'success', message: res.data.msg})
                // if(this.form.id){
                // 	this.getList()
                // }else{
                // 	this.$router.push('/road-traffii/illegal/index')
                // }
                this.getList()
              } else {
                this.$message.error(res.data.msg)
              }
            })
            .catch((e) => {
              this.saveLoading = false
              this.$message.error(e.message)
            })
        } else {
          return false
        }
      })
    },

    /* 调整差异 add 202309152231 */
    adjustDifference() {
      console.log('adjustDifference',this.form.id)
      if(this.form.images.length > 1){
        this.showAdjustModal = true;
      }
      else{
        this.$message({
          showClose: true,
          message: '低于2张图片无法调整差异',
          type: 'error'
        });
      }

    },

    /* 立即比对 add 202309152234*/
    compareNow() {
      if(this.form.images.length > 1){
        console.log('compareNow',this.form.id)
        this.compareLoading = true
        this.$http
          .post('/illegal/compareImg', this.form)
          .then((res) => {
            this.compareLoading = false
            if (res.data.code === 0) {
              this.$message({ type: 'success', message: res.data.msg })
              this.handleImagesChange(res.data.data.url)
              this.form.diff_points = res.data.data.points
            } else {
              this.$message.error(res.data.msg)
              this.compareLoading = false
            }
          })
          .catch((e) => {
            this.compareLoading = false
            this.$message.error(e.message)
          })
      }
      else{
        this.$message({
          showClose: true,
          message: '无法进行图片比对',
          type: 'error'
        });
      }

    },
    /* 更新图片显示 add 202309160935*/
    handleImagesChange(val) {
      console.log(val)
      if(this.form.images.length == 2){
        this.form.images.push(val)
      }

      if(this.form.images.length == 3){
        this.form.images.splice(2,1,val)
      }

    },
    /* 通过地址获取上一次的图片*/
    async getLastImageByAddress() {
      this.$http
        .post('/illegal/getLastImageByAddress', {address: this.address})
        .then((res) => {
          if (res.data.code === 0) {
            this.form.images = []
            this.form.images.unshift(res.data.data.url)
          }else{
            this.form.images = []
          }
        })
        .catch((e) => {
          this.$message.error(e.message)
        })
    },

    goHistory() {
      this.$router.push({
        path: '/road-traffii/illegal/history',
        query: {address_detailed: this.form.address, operation_no: this.form.operation_no}
      })
    }
  }
}
</script>

<style scoped>
  ._card {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  ._form {
    width: 400px;
  }

  .form-title {
    padding-left: 20px;
    height: 36px;
    background: linear-gradient(90deg, #0758C4 0%, rgba(7, 88, 196, 0) 100%);
    border-radius: 2px 2px 2px 2px;
    opacity: 1;
    line-height: 36px;
    font-size: 16px;
    font-weight: 500;
    color: #FFFFFF;
    margin-bottom: 15px;
  }

  .logDiv {
    margin-left: 100px;
    line-height: 36px;
    border: 1px solid #c0c4cc;
    margin-bottom: 10px;
    text-align: center;
    cursor: pointer;
  }
</style>
